<script setup lang="ts">
import * as monaco from "monaco-editor";
import { defineProps, ref, withDefaults, toRaw, watchEffect, watch } from "vue";
import { onMounted } from "vue";

const codeEditorRef = ref();
const codeEditor = ref();
const value = ref("hello world");

interface Props {
  value: string;
  language: string;
  handleChange: (v: string) => void;
}

const props = withDefaults(defineProps<Props>(), {
  value:
    "class Main {\n" +
    "    public static void main (String[] args) {\n" +
    "        System.out.print(2);\n" +
    "    }\n" +
    "}",
  language: "java",
  handleChange: (v: string) => {
    console.log(v);
  },
});
onMounted(() => {
  if (!codeEditorRef.value) {
    return;
  }

  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      enabled: true,
    },
    readOnly: false,
    theme: "vs-dark",
  });
  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
  });
});

watch(
  () => props.language,
  () => {
    if (codeEditor.value) {
      monaco.editor.setModelLanguage(
        toRaw(codeEditor.value).getModel(),
        props.language
      );
    }
  }
);
</script>

<template>
  <div id="code-editor" ref="codeEditorRef" style="min-height: 70vh" />
</template>

<style scoped></style>
